package com.easy.controller;

import com.easy.bean.Purchase_order;
import com.easy.service.PurchaseOrderService;
import com.easy.util.Page;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/api/purchase_order")
public class PurchaseOrderController {

    @Autowired
    PurchaseOrderService purchaseOrderService;

    // 新增订单
    @PostMapping
    public Result add(@RequestBody Purchase_order order) {
        try {
            return Result.success(purchaseOrderService.add(order));
        } catch (IllegalArgumentException e) {
            return Result.fail(400, e.getMessage());
        }
    }

    // 编辑订单
    @PutMapping("/{id}")
    public Result edit(@PathVariable("id") Integer id, @RequestBody Purchase_order order) {
        order.setId(id);
        return Result.success(purchaseOrderService.edit(order));
    }

    // 删除订单
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") Integer id) {
        return Result.success("删除数据", purchaseOrderService.del(id));
    }

    // 查询所有订单（可模糊查询）
    @GetMapping
    public Result all(
            @RequestParam(name = "supplier_id", required = false) Integer supplierId,
            @RequestParam(name = "material_id", required = false) Integer materialId
    ) {
        return Result.success(purchaseOrderService.all(supplierId, materialId));
    }

    // 查询单个订单
    @GetMapping("/{id}")
    public Result one(@PathVariable("id") Integer id) {
        return Result.success(purchaseOrderService.one(id));
    }

    // 分页查询订单
    @GetMapping("page")
    public Result page(Page page, Purchase_order order){
        purchaseOrderService.page(page, order);
        return Result.success(page);
    }
}